import webbrowser
import time,config
import config,autologin,dohttp
import wifiauthtool
import threading
import requests
from autoget_remaining_usage import sendreq,get_usage_percent
from PyQt5.QtWidgets import QMainWindow,QMessageBox,QApplication
from PyQt5.QtCore import QThread,pyqtSignal,Qt
from window2 import window2
from window1_ui import Ui_MainWindow
from math import floor

class window1(QMainWindow):
    def __init__(self,parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()

        width = config.get_scale_num(269)
        height = config.get_scale_num(395)
        
        try:
            x = config.gcon("setting", "x")
            y = config.gcon("setting", "y")
            
        except:#若获取到空文本，转换类型会报错，这时截获然后设置初始位置
            screan = QApplication.desktop().screenGeometry()
            x = screan.width()-width
            y = floor(screan.height()/2-height+screan.height()/4)
        
        self.setFixedSize(width,height)
        self.ui.setupUi(self)
        self.move(x,y)
        self.setWindowFlag(Qt.WindowStaysOnTopHint,True)

        self.ui.pushButton_1.clicked.connect(self.on_nolimit)
        self.ui.pushButton_2.clicked.connect(self.on_urltrans)
        self.ui.pushButton_3.clicked.connect(self.on_jw)
        self.ui.pushButton_4.clicked.connect(self.on_bt)
        self.ui.pushButton_5.clicked.connect(self.on_email)
        self.ui.pushButton_6.clicked.connect(self.on_oa)
        self.ui.pushButton_7.clicked.connect(self.on_touda)

        self.clock = clock()
        self.clock.update_signal.connect(self.clockhandle)
        self.clock.start() 

        self.save_thread = threading.Thread(target=self.save_window_position)
        self.save_thread.setDaemon(True)
        self.save_thread.start()  
    def closeEvent(self, event):
        msgBox = QMessageBox(self)
        msgBox.setIcon(QMessageBox.Question)
        msgBox.setText("确定要退出吗？")
        yesButton = msgBox.addButton("关闭", QMessageBox.YesRole)
        noButton = msgBox.addButton("隐藏", QMessageBox.NoRole)
        cancelButton = msgBox.addButton("取消", QMessageBox.RejectRole)
        
        msgBox.exec()
        
        if msgBox.clickedButton() == yesButton:
            event.accept()  # 关闭窗口
            exit()
        elif msgBox.clickedButton() == noButton:
            self.keyhandle()
            event.ignore()  # 忽略关闭事件
        else:
            event.ignore()  # 忽略关闭事件        
    def on_nolimit(self):
        #os.system("python autologin.py")
        try:
            m = autologin.run()
        except Exception as e:
            QMessageBox.warning(self, "登陆失败", f"登陆失败，进行登录请求时出现错误:{e}")
            return
        if isinstance(m,str):
            QMessageBox.warning(self, "登陆失败", f"登陆失败，{m}")
        elif isinstance(m,requests.Session):
            self.session = m
    def on_urltrans(self):
        self.window2 = window2()
        self.window2.win1 = self
        self.window2.show()
    def on_jw(self):
        webbrowser.open("https://jw.stu.edu.cn")
    def on_bt(self):
        webbrowser.open("http://phoenix.stu.edu.cn/bt/default.aspx")
    def on_email(self):
        webbrowser.open("https://partner.outlook.cn/mail/")
    def on_oa(self):
        webbrowser.open("http://oa.stu.edu.cn/")
    def on_touda(self):
        webbrowser.open("https://www.stu.edu.cn/kstd.htm")
    def clockhandle(self,data):
        t = data.split("|||")
        self.ui.text1.setHtml(t[0])
        self.ui.progressBar.setValue(int(t[1]))      
 #取消置顶防止未响应   
    def keyhandle(self):
        if self.isVisible():
            if hasattr(self,"window2"):
                self.window2.hide()
            self.setWindowFlag(Qt.WindowStaysOnTopHint,False)
            self.hide()
        else:    
            self.setWindowFlag(Qt.WindowStaysOnTopHint,True) 
            self.show()
    def save_window_position(self):
        while True:
            config.wcon("setting", "x", self.pos().x())
            config.wcon("setting", "y", self.pos().y())
            time.sleep(1)
    def detect_vpnlogin(self):
        if config.gcon("setting","keep_twfid") != "yes":
            return
        try:
            r = dohttp.get("https://webvpn.stu.edu.cn/por/conf.csp?apiversion=1",headers={
                                            "Content-Type": "application/x-www-form-urlencoded",
                                            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0",
                                            "Cookie":f"TWFID={config.gcon('setting','twfid')}"})
            if "error" not in r and r is not None:
                            #print(r.content.decode())

                            if "unexpected user service" in r.content.decode():#检测是否是在登录页面
                                login_WebVPN()
                                print("检测到掉线，正在重新自动登录")
                            else:
                                upload_key()
                                print("心跳一次")
        except Exception as e:
            print(f"检测登录时出现错误，{e}")              
def upload_key():
    try:
        name = config.gcon("setting","vpnname")
    except:
        name = config.gcon("setting","name")

    try:
        if config.gcon("setting","upload_twfid") == "yes":
            url = config.gcon("setting","upload_url")
            key = config.gcon("setting","twfid")
            res = requests.post(url,
                                data={'name':f'{name}',
                                      'key':f'{key}'},
                                headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0"},
                                verify=False,
                                timeout=3)
            print(res)
            if res != "error":
                print(res.text)
    except Exception as e:
        print(f"upload_key时出现错误：{e}")


            
def login_WebVPN():
    try:
        m = autologin.run(False)
        upload_key()
        if isinstance(m,requests.Session):
            window1.session = m
        else:
            print(f"自动webvpn:{m}")
    except Exception as e:
        print(f"启动登录webvpn出现错误: {e}")
def detect_vpnlogin():
    if config.gcon("setting","keep_twfid") != "yes":
        return
    try:
        r = dohttp.get("https://webvpn.stu.edu.cn/por/conf.csp?apiversion=1",headers={
                                        "Content-Type": "application/x-www-form-urlencoded",
                                        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0",
                                        "Cookie":f"TWFID={config.gcon('setting','twfid')}"})
        if "error" not in r and r is not None:
                        #print(r.content.decode())

                        if "unexpected user service" in r.content.decode():#检测是否是在登录页面
                            login_WebVPN()
                            print("检测到掉线，正在重新自动登录")
                        else:
                            upload_key()
                            print("心跳一次")
    except Exception as e:
        print(f"检测登录时出现错误，{e}")          
    
class clock(QThread):
    update_signal = pyqtSignal(str)
    def __init__(self):
        super().__init__()
        print("clock init")
        detect_vpnlogin()
    def run(self):
        while True:
            #self.load_data()
            try:
                data = sendreq()
                if "临时" in data: 
                    data = "<p1>当前处于学校无限流量状态</p1>"
                if "请求剩余流量时出错" in data:
                    data = "<p1>请求剩余流量时出错</p1>"
                usage_percent = get_usage_percent(data) 
                data_to_emit = f"{data}|||{usage_percent}"
                self.update_signal.emit(data_to_emit)
            except Exception as e:
                print(f"An error occurred: {e}")  # 打印异常信息，防止线程崩溃

            time.sleep(60)

            try:
                # 防止掉认证
                username = config.gcon("setting", "name")
                password = config.gcon("setting", "password")
                wifiauthtool.sendreq(f"opr=pwdLogin&userName={username}&pwd={password}&ipv4or6=&rememberPwd=1")
                # detect_vpnlogin() 删去 有可能判断偏差
            except Exception as e:
                print(f"An error occurred during authentication: {e}")  # 打印异常信息





